 import requests
from app import app, db
from app.models import EtfFund, CollectLog
from datetime import datetime

API_URL = 'http://www.etf.group/data/api1.php?page=1&limit=9999'

def fetch_etf():
    try:
        resp = requests.get(API_URL, timeout=10)
        data = resp.json()
        items = data['rows']['item']
        count = 0
        for item in items:
            fund = EtfFund.query.filter_by(code=item['code']).first()
            if not fund:
                fund = EtfFund()
            for k, v in item.items():
                if hasattr(fund, k):
                    setattr(fund, k, v)
            fund.updated_at = datetime.utcnow()
            db.session.add(fund)
            count += 1
        db.session.commit()
        log = CollectLog(fund_type='etf', api_url=API_URL, status='success', count=count, error='')
        db.session.add(log)
        db.session.commit()
        print(f"ETF采集完成，共{count}条")
    except Exception as e:
        db.session.rollback()
        log = CollectLog(fund_type='etf', api_url=API_URL, status='fail', count=0, error=str(e))
        db.session.add(log)
        db.session.commit()
        print(f"采集失败: {e}")

if __name__ == '__main__':
    with app.app_context():
        fetch_etf()
